// 通用JavaScript工具函数

// API请求包装器
async function apiRequest(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        }
    };

    const finalOptions = { ...defaultOptions, ...options };

    try {
        const response = await fetch(url, finalOptions);
        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.error || '请求失败');
        }

        return data;
    } catch (error) {
        console.error('API Error:', error);
        throw error;
    }
}

// 获取目标列表
async function getObjectives(filters = {}) {
    const params = new URLSearchParams(filters);
    return apiRequest(`/api/objectives?${params}`);
}

// 创建目标
async function createObjective(data) {
    return apiRequest('/api/objectives', {
        method: 'POST',
        body: JSON.stringify(data)
    });
}

// 更新目标
async function updateObjective(id, data) {
    return apiRequest(`/api/objectives/${id}`, {
        method: 'PUT',
        body: JSON.stringify(data)
    });
}

// 删除目标
async function deleteObjective(id) {
    return apiRequest(`/api/objectives/${id}`, {
        method: 'DELETE'
    });
}

// 获取项目列表
async function getProjects(filters = {}) {
    const params = new URLSearchParams(filters);
    return apiRequest(`/api/projects?${params}`);
}

// 创建项目
async function createProject(data) {
    return apiRequest('/api/projects', {
        method: 'POST',
        body: JSON.stringify(data)
    });
}

// 更新工作状态
async function updateStatus(data) {
    return apiRequest('/api/status', {
        method: 'POST',
        body: JSON.stringify(data)
    });
}

// 获取团队状态
async function getTeamStatus() {
    return apiRequest('/api/status/team');
}

// AI查询
async function aiQuery(query) {
    return apiRequest('/api/query', {
        method: 'POST',
        body: JSON.stringify({ query })
    });
}

// 进度条渲染
function renderProgressBar(progress, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    let colorClass = 'danger';
    if (progress >= 70) colorClass = 'success';
    else if (progress >= 40) colorClass = 'warning';

    container.innerHTML = `
        <div class="progress">
            <div class="progress-bar ${colorClass}" style="width: ${progress}%"></div>
        </div>
        <span style="font-size: 0.875rem; color: var(--text-secondary);">${progress}%</span>
    `;
}

// 状态标签渲染
function getStatusBadge(status) {
    const statusMap = {
        'active': { class: 'badge-primary', text: '进行中' },
        'completed': { class: 'badge-success', text: '已完成' },
        'cancelled': { class: 'badge-danger', text: '已取消' },
        'on_hold': { class: 'badge-warning', text: '暂停' },
        'on_site': { class: 'badge-success', text: '在岗' },
        'remote': { class: 'badge-primary', text: '远程' },
        'leave': { class: 'badge-warning', text: '请假' },
        'out': { class: 'badge-secondary', text: '外出' }
    };

    const config = statusMap[status] || { class: 'badge-secondary', text: status };
    return `<span class="badge ${config.class}">${config.text}</span>`;
}

// 日期格式化
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 1rem 1.5rem;
        border-radius: 8px;
        background: white;
        box-shadow: var(--shadow-lg);
        z-index: 9999;
        animation: slideIn 0.3s ease-out;
    `;

    const colors = {
        success: 'var(--success-color)',
        error: 'var(--danger-color)',
        warning: 'var(--warning-color)',
        info: 'var(--primary-color)'
    };

    notification.style.borderLeft = `4px solid ${colors[type] || colors.info}`;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-in';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// 模态框控制
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.classList.add('active');
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.classList.remove('active');
}

// 登出
async function logout() {
    try {
        await apiRequest('/auth/logout', { method: 'POST' });
        window.location.href = '/auth/login';
    } catch (error) {
        showNotification('登出失败', 'error');
    }
}

// Markdown渲染器（简化版）
function renderMarkdown(text) {
    if (!text) return '';

    // 移除末尾的JSON数据块
    text = text.replace(/```json[\s\S]*?```\s*$/g, '');
    text = text.replace(/json\s*\{[\s\S]*?\}\s*$/g, '');

    // 移除Markdown表格（转换为列表）
    const lines = text.split('\n');
    const processedLines = [];
    let inTable = false;

    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();

        // 检测表格行
        if (line.includes('|') && (line.match(/\|/g) || []).length >= 2) {
            if (!inTable) {
                inTable = true;
                processedLines.push(''); // 空行分隔
            }
            // 跳过表头分隔行
            if (line.match(/^\|[\s\-:|]+\|$/)) continue;

            // 将表格行转换为列表项
            const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
            if (cells.length > 0) {
                processedLines.push('- ' + cells.join(': '));
            }
        } else {
            if (inTable) {
                inTable = false;
                processedLines.push(''); // 空行分隔
            }
            processedLines.push(lines[i]);
        }
    }

    text = processedLines.join('\n');

    // 转义HTML
    text = text.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;');

    // 处理标题
    text = text.replace(/^## (.+)$/gm, '<h2 style="color: var(--primary-color); margin-top: 1.5rem; margin-bottom: 0.75rem; font-size: 1.25rem; font-weight: 600; border-bottom: 2px solid var(--primary-color); padding-bottom: 0.5rem;">$1</h2>');
    text = text.replace(/^### (.+)$/gm, '<h3 style="color: var(--text-primary); margin-top: 1rem; margin-bottom: 0.5rem; font-size: 1.1rem; font-weight: 600;">$1</h3>');
    text = text.replace(/^#### (.+)$/gm, '<h4 style="color: var(--text-primary); margin-top: 0.75rem; margin-bottom: 0.5rem; font-size: 1rem; font-weight: 600;">$1</h4>');

    // 处理粗体
    text = text.replace(/\*\*(.+?)\*\*/g, '<strong style="color: var(--primary-color);">$1</strong>');

    // 处理有序列表
    text = text.replace(/^\d+\.\s+(.+)$/gm, '<li style="margin-left: 1.5rem; margin-bottom: 0.5rem;">$1</li>');

    // 处理无序列表
    text = text.replace(/^[-•]\s+(.+)$/gm, '<li style="margin-left: 1.5rem; margin-bottom: 0.5rem; list-style-type: disc;">$1</li>');

    // 包裹列表
    text = text.replace(/(<li[^>]*>.*<\/li>)/s, '<ul style="margin: 0.5rem 0;">$1</ul>');

    // 处理代码块
    text = text.replace(/```([^`]+)```/gs, '<pre style="background: var(--background-color); padding: 1rem; border-radius: 6px; overflow-x: auto; margin: 0.5rem 0;"><code>$1</code></pre>');

    // 处理段落（空行分隔）
    text = text.split('\n\n').map(para => {
        if (para.trim() && !para.match(/^<[hul]/)) {
            return `<p style="margin: 0.75rem 0; line-height: 1.6;">${para}</p>`;
        }
        return para;
    }).join('\n');

    return text;
}

// 动画CSS
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);